package com.hilda.HTMLParserTesting.webViewParser;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hilda.HTMLParserTesting.utils.SdCardUtils;

public class HildaWebView {
	private Context mContext;
	private URL mURL;
	private SdCardUtils mSdCardUtils;
	private WebView mWebview;

	public HildaWebView(Context c) {
		mContext = c;
		mSdCardUtils = new SdCardUtils(mContext);
		mWebview = new WebView(mContext);

		mWebview.getSettings().setJavaScriptEnabled(true);
		mWebview.getSettings().setPluginsEnabled(true);
		

	}

	public void parse(String url) {

		Log.i("crawDroid", "Start HildaWebView parser " + url);

		if (!url.endsWith("/"))
			url += "/";

		try {
			mURL = new URL(url);
		} catch (MalformedURLException e) {
			Log.e("crawDroid", ".HildaWebView: " + e.getMessage());
		}

		
		mWebview.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageFinished(WebView view, String url) {
				File file = mSdCardUtils.prepareFile(mURL, null);

				mWebview.saveWebArchive(file.getAbsolutePath());
				Log.i("crawDroid", "Finish HildaWebView parser " + file.getAbsolutePath());
				super.onPageFinished(view, url);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				mWebview.loadUrl(mURL.toExternalForm());
				return super.shouldOverrideUrlLoading(view, url);
			}

		});
//		mWebview.loadUrl(mURL.toExternalForm());
//		DowloadWebTask dowloadWebTask = new DowloadWebTask();
//		dowloadWebTask.execute();

	}

	private class DowloadWebTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			return null;
		}
	}
}
